import com.zcf.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by Administrator on 2017/3/1.
 */
public class Hibernate {
    public Session getSession(){
        Configuration configuration  = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session =  sessionFactory.openSession();
        return session;
    }
    @Test
    public void configTest(){
        Configuration configuration  = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        SessionFactory sessionFactory = configuration.buildSessionFactory();

        Session session =  sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User user = new User();
        user.setUsername("bbb");
        user.setPassword("123");
        session.save(user);
        transaction.commit();
        System.out.println(user);

    }

    @Test
    public void getTest(){
       Session session = getSession();
       Transaction transaction = session.beginTransaction();
       User user = null;
       user = (User) session.createQuery("from User u where u.username = ?")
               .setParameter(0,"bbb")
               .uniqueResult();
       session.delete(user);
       transaction.commit();
       session.close();
        System.out.println(user);
    }

    @Test
    public void getId(){
        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        User user = null;
        user = (User) session.get(User.class,1);
        transaction.commit();
        session.close();
        System.out.println(user);
    }

    @Test
    public void testBean(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
        SessionFactory sf  = (SessionFactory) ac.getBean("sessionFactory");
        System.out.println(sf);
    }

}
